package com.filter;

import com.config.WebSecurityConfig;
import com.util.AuthenticationAdaptor;
import com.util.UserInfo;
import com.util.JwtTokenUtils;
import com.util.UserUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private static final String TOKEN_PREFIX = "Bearer ";

    private JwtTokenUtils tokenProvider;
    private AuthenticationAdaptor authenticationAdaptor;

    public JwtAuthenticationTokenFilter(JwtTokenUtils tokenProvider,
                                        AuthenticationAdaptor authenticationAdaptor) {
        this.tokenProvider = tokenProvider;
        this.authenticationAdaptor = authenticationAdaptor;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = resolveToken(request);
        if (token != null && !"".equals(token.trim()) && SecurityContextHolder.getContext().getAuthentication() == null) {
            if (tokenProvider.validToken(token)) {
                // 从token中获取用户信息并存储
                UserInfo userInfo = tokenProvider.getUserInfo(token);
                UserUtils.setUser(userInfo);

                // 添加鉴权用户信息
                Authentication authentication = authenticationAdaptor.adapte(userInfo);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        try {
            filterChain.doFilter(request, response);
        } finally {
            // 移除用户信息
            UserUtils.clear();
        }

    }

    private String resolveToken(HttpServletRequest request) {

        String bearerToken = request.getHeader(WebSecurityConfig.AUTHORIZATION_HEADER);
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(TOKEN_PREFIX)) {
            return bearerToken.substring(TOKEN_PREFIX.length());
        }
        String jwt = request.getParameter(WebSecurityConfig.AUTHORIZATION_TOKEN);
        if (StringUtils.hasText(jwt)) {
            return jwt;
        }
        return null;
    }
}
